package com.csw.encryptiontechnology.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;

public class Base64File {
	public static void main(String[] args) {
		try {
			String str = Base64File.encodeBase64FileByPath("C:\\Windows\\Media\\chimes.wav");
			System.out.println(str);
			String outUrl = "C:\\Users\\1\\Desktop\\新建文件夹";
			// String outUrl =
			// ResourceUtils.getURL("classpath:static").getPath().replace("%20", "
			// ").substring(1);
			Base64File.decoderBase64File(str, outUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String encodeBase64FileByPath(String path) throws Exception {
		File file = new File(path);
		byte[] buffer;
		try(FileInputStream is = new FileInputStream(file)) {
			buffer = new byte[(int) file.length()];
			while (is.read(buffer) > 0) {
				is.close();
			}
		}
		return AesUtil.base64Encode(buffer);

	}

	public static String encodeBase64File(MultipartFile file) throws Exception {
		byte[] byt = null;
		String res = null;
		try {
			InputStream is = file.getInputStream();
			byt = new byte[is.available()];
			while (is.read(byt)>0){
				res = AesUtil.base64Encode(byt);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;

	}

	/**
	 * 将base64字符解码保存文件
	 * 
	 * @param base64Code
	 * @param targetPath
	 * @throws Exception
	 */

	public static void decoderBase64FileByPath(String base64Code, String targetPath) throws Exception {
		byte[] buffer = AesUtil.base64Decode(base64Code);
		try(FileOutputStream out = new FileOutputStream(targetPath + "/1.wav")) {
			out.write(buffer);
			out.close();
		}

	}

	public static void decoderBase64File(String base64Code, String targetPath) throws Exception {

		// res 接收的参数（编码后的字符串）
		byte[] buffer = AesUtil.base64Decode(base64Code);
		File packageFile = new File(targetPath);
		if (!packageFile.exists()) {
			packageFile.mkdir();
		}
		try(FileOutputStream out = new FileOutputStream(targetPath + "\\" + packageFile.getName())) {
			out.write(buffer);
			out.close();
		}

	}

}
